<script>
import ProjectSelector from "@/components/Selector/ProjectSelector.vue";
import { defineComponent } from "vue";
import {
  add,
  allProjectDl,
  list,
  preview,
  split
} from "@/api/subsidiaryAccount.ts";
import ExpenseLedgerSelector from "@/components/Selector/ExpenseLedgerSelector.vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import { guid } from "@/utils/idUtils.ts";

export default defineComponent({
  name: "subsidiary-account",
  components: { ExpenseLedgerSelector, ProjectSelector },
  data() {
    return {
      uploadDisplay: false,
      tableData: [],
      selected: [],
      query: {
        projectId: "",
        // 当前页码
        currPage: 1,
        // 页尺寸
        pageSize: 10,
        // 页总记录数
        // 刷新按钮
        lst: false
      },
      pageTotal: 0,
      splitDisplay: false,
      splitMapping: {},
      curRow: { id: 0 },
      expenses: [],
      singleSubDisplay: false,
      singleSubDisplayRes: false,
      year: new Date(),
      projectName: "",
      htmlRes: "",
      importDisplay: false,
      projectIds: [],
      projectExportDisplay: false,
      importData: {
        /**
         * 摘要
         */
        abstractContent: "",
        /**
         * 贷方金额
         */
        credit: 0,
        /**
         * 借方金额
         */
        debit: 0,
        /**
         * 研发费用
         */
        expenses: [],
        /**
         * 借或贷
         */
        flow: "",
        /**
         * 开始时间
         */
        startTime: new Date(),
        /**
         * 凭证
         */
        voucher: ""
      }
    };
  },
  watch: {
    query: {
      handler() {
        this.getList();
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    async getList() {
      if (!this.query.projectId) {
        this.tableData = [];
        return;
      }
      let res = await list({
        current: this.query.currPage,
        size: this.query.pageSize,
        projectId: this.query.projectId
      });
      this.tableData = res.data.records;
      this.pageTotal = res.data.total;
    },
    // 数据页码长度变化
    pageSizeChange(pageSize) {
      this.query.pageSize = pageSize;
      this.query.currPage = 1;
      this.getList();
    },
    // 数据页码变化
    currPageChange(pageIndex) {
      this.query.currPage = pageIndex;
      this.getList();
    },
    handleSelectionChange(rows) {
      this.selected = rows;
    },
    openSplit(item) {
      if (item.expenses.length !== 1 && item.expenses[0].isFinal) {
        ElMessage({
          message: "该辅助帐已被分割，无法继续分割",
          type: "error"
        });
        return;
      }
      this.splitDisplay = true;
      this.curRow = item;
      this.expenses = [];
    },
    addExpense() {
      this.expenses.push({ uuid: guid() });
    },
    delExp(row) {
      for (let i = 0; i < this.expenses.length; i++) {
        console.log(this.expenses[i].uuid, row.uuid);
        if (this.expenses[i].uuid === row.uuid) {
          this.expenses.splice(i, 1);
          break;
        }
      }
    },
    exportProject() {
      allProjectDl(this.projectIds, dayjs(this.year).format("YYYY"));
    },
    openPreviewProject() {
      if (!this.query.projectId) {
        ElMessage({
          message: "请先选择项目",
          type: "error"
        });
        return;
      }
      this.singleSubDisplay = true;
    },
    projectChange(item) {
      this.projectName = item.name;
    },
    async previewProject() {
      let res = await preview(
        this.query.projectId,
        dayjs(this.year).format("YYYY")
      );
      if (typeof res != "string") {
        ElMessage({
          message: res.msg,
          type: "error"
        });
        return;
      }
      this.htmlRes = res;
      this.singleSubDisplayRes = true;
      // eslint-disable-next-line vue/valid-next-tick
      // this.$nextTick(() => {
      //   this.iframeLoad();
      // });
    },
    iframeLoad() {
      document.getElementById("iframe").height =
        document.getElementById("iframe").contentWindow.document.body
          .scrollHeight + 100;
    },
    openImportData() {
      this.importDisplay = true;
      this.expenses = [];
      this.importData = {
        /**
         * 摘要
         */
        abstractContent: "",
        /**
         * 贷方金额
         */
        credit: 0,
        /**
         * 借方金额
         */
        debit: 0,
        /**
         * 研发费用
         */
        expenses: [],
        /**
         * 借或贷
         */
        flow: "",
        /**
         * 开始时间
         */
        startTime: new Date(),
        /**
         * 凭证
         */
        voucher: ""
      };
    },
    async splitMoney() {
      let res = await split({
        expensePid: this.curRow.expenses[0].id,
        expenses: this.expenses
      });
      if (res.code !== 200) {
        ElMessage({
          message: res.msg,
          type: "error"
        });
      } else {
        ElMessage({
          message: "分割成功",
          type: "success"
        });
        this.splitDisplay = false;
        await this.getList();
      }
    },
    async importDataFun() {
      let res = await add({
        ...this.importData,
        startTime: dayjs(this.importData.startTime).format(
          `YYYY-MM-DDTHH:mm:ss`
        ),
        expenses: this.expenses,
        projectId: this.query.projectId
      });
      if (res.code === 200) {
        ElMessage({
          message: "导入成功",
          type: "success"
        });
      } else {
        ElMessage({
          message: res.msg,
          type: "error"
        });
      }
      this.importDisplay = false;
      await this.getList();
    }
  }
});
</script>

<template>
  <div>
    <header>
      <ProjectSelector v-model="query.projectId" @change="projectChange" />
      &nbsp;
      <el-button type="primary" @click="openPreviewProject">
        预览当前项目辅助帐
      </el-button>
      <el-button type="primary" @click="projectExportDisplay = true">
        辅助帐导出</el-button
      >
      <el-button type="primary" @click="openImportData"> 辅助帐录入</el-button>
    </header>

    <!--数据-->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="voucher" label="凭证号" />
      <el-table-column prop="abstractContent" label="摘要" />
      <el-table-column prop="startTime" label="开始时间" />
      <el-table-column prop="flow" label="流向" />
      <el-table-column prop="debit" label="借方金额" />
      <el-table-column prop="credit" label="贷方金额" />
      <el-table-column prop="expenses" label="费用分布">
        <template v-slot="scope">
          {{ scope.row.expenses.map(s => `${s.ledger}：${s.money}`).join(",") }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button
            type="primary"
            :disabled="scope.row.expenses[0].isFinal"
            @click="openSplit(scope.row)"
            >数据分割
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 常规数据分页开始 -->
    <el-pagination
      v-model::current-page="query.currPage"
      v-model:page-size="query.pageSize"
      :total="pageTotal"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      layout="prev,pager,next,jumper,sizes,total"
      style="margin-top: 10px"
      @size-change="pageSizeChange"
      @current-change="currPageChange"
    />
    <el-dialog
      v-model="splitDisplay"
      :title="
        '辅助帐分割:' +
        curRow?.expenses?.[0]?.ledger +
        ' ' +
        curRow?.expenses?.[0]?.money
      "
      width="800"
      destroy-on-close
    >
      <el-table
        :data="expenses"
        border
        style="width: 100%; margin-top: 20px"
        row-key="uuid"
      >
        <el-table-column prop="expenses" width="300px" label="子费用分类">
          <template v-slot="scope">
            <ExpenseLedgerSelector
              v-model="scope.row.ledgerId"
              :check-strictly="false"
              :parent-id="curRow?.expenses?.[0].ledgerId"
            />
          </template>
        </el-table-column>
        <el-table-column label="金额">
          <template v-slot="scope">
            <el-input v-model="scope.row.money" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="danger" @click="delExp(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button style="margin-top: 20px" @click="addExpense"
        >添加一项
      </el-button>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="splitMoney"> 立即分割</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="singleSubDisplay"
      :title="projectName + '辅助帐生成'"
      width="500"
    >
      <el-dialog
        v-model="singleSubDisplayRes"
        width="1200"
        :title="projectName + '辅助帐'"
        append-to-body
        fullscreen
      >
        <iframe
          id="iframe"
          :srcdoc="htmlRes"
          style="width: 100%"
          @load="iframeLoad"
        />
      </el-dialog>
      年份：
      <el-date-picker v-model="year" type="year" placeholder="请选择年份" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="previewProject">
            预览辅助帐
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="projectExportDisplay" :title="'辅助帐导出'" width="500">
      年份：
      <el-date-picker v-model="year" type="year" placeholder="请选择年份" />
      <br />
      <br />
      项目：
      <project-selector v-model="projectIds" multiple />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="exportProject">
            导出辅助帐
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="importDisplay"
      :title="projectName + '辅助帐导入'"
      width="640"
      destroy-on-close
    >
      <el-form :model="importData" label-width="auto" style="max-width: 600px">
        <el-form-item label="凭证号">
          <el-input
            v-model="importData.voucher"
            placeholder="请输入凭证号，例如：计-01"
          />
        </el-form-item>
        <el-form-item label="摘要">
          <el-input
            v-model="importData.abstractContent"
            placeholder="请输入摘要"
          />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="importData.startTime"
            type="date"
            placeholder="请选择开始时间"
          />
        </el-form-item>
        <el-form-item label="流向">
          <el-select
            v-model="importData.flow"
            placeholder="请输入流向，填：借或贷"
          >
            <el-option value="借" label="借" />
            <el-option value="贷" label="贷" />
          </el-select>
        </el-form-item>
        <el-form-item label="借方金额">
          <el-input-number
            v-model="importData.debit"
            placeholder="请输入借方金额"
          />
        </el-form-item>
        <el-form-item label="贷方金额">
          <el-input-number
            v-model="importData.credit"
            placeholder="请输入贷方金额"
          />
        </el-form-item>
        费用分类
        <el-table
          :data="expenses"
          border
          style="width: 100%; margin-top: 20px"
          row-key="uuid"
        >
          <el-table-column prop="expenses" width="250px" label="费用分类">
            <template v-slot="scope">
              <ExpenseLedgerSelector
                v-model="scope.row.ledgerId"
                :check-strictly="false"
                :parentValue="curRow.id"
              />
            </template>
          </el-table-column>
          <el-table-column label="金额">
            <template v-slot="scope">
              <el-input-number v-model="scope.row.money" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button type="danger" @click="delExp(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button style="margin-top: 20px" @click="addExpense"
          >添加一项
        </el-button>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="importDataFun"> 导入</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
.layout-card {
  margin-top: 20px;
}
</style>
